<script setup lang='ts'>
import type { FormItemRule } from 'element-plus'
import type { PlusColumn } from 'plus-pro-components'

import { useAddCategoryAttribute, useAttributeInfo, useEditCategoryAttribute } from '@fl/api/mall-api'
import { SubmitBtn } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'

const emits = defineEmits(['success'])
const attributeVisible = defineModel<boolean>('attributeVisible', { required: true })
const currentCategoryId = defineModel<number>('currentCategoryId', { required: true })
console.log(currentCategoryId, 'currentCategoryId')
const attributeDialogType = defineModel<string>('attributeDialogType', { required: true })
const attributeId = defineModel<string>('attributeId', { required: true })
const formRef = ref()
const attributeValueList = ref<any[]>([
    {
        value: '',
    },
])
type Istate = {
    attributeName: string
    // attributeType: number
    attributeValue: string
    categoryId: number
    id?: number | string
    isCustom: number
    isRequired: number
    isSaleAttribute: number
}
const isRequired = ref<boolean>(false)
const isSaleAttribute = ref<boolean>(false)
const isCustom = ref<boolean>(false)
const initialState = {
    attributeName: '',
    // attributeType: 1,
    attributeValue: '',
    categoryId: currentCategoryId.value,
    id: '',
    isCustom: 0,
    isRequired: 0,
    isSaleAttribute: 0,
}
const { createMessage } = useMessage()
const state = ref<Istate>(cloneDeep(initialState))
const title = computed(() => {
    return attributeDialogType.value === 'add' ? '新增属性' : attributeDialogType.value === 'edit' ? '编辑属性' : '查看属性'
})
const { isPending: isAddCategoryAttributePending, mutate: addCategoryAttributeMutate } = useAddCategoryAttribute()
const { isPending: isEditCategoryAttributePending, mutate: editCategoryAttributeMutate } = useEditCategoryAttribute()
const { data: attributeInfo, isLoading: attributeInfoLoading } = useAttributeInfo(attributeId)
const isPending = computed(() => {
    return isAddCategoryAttributePending.value || isEditCategoryAttributePending.value
})

watchEffect(() => {
    if (attributeId.value) {
        if (attributeInfo.value) {
            state.value = {
                ...attributeInfo.value,
            }
            attributeValueList.value = JSON.parse(state.value.attributeValue).map((item: any) => {
                return {
                    value: item.value,
                }
            })
            isCustom.value = Boolean(Number(state.value.isCustom))
            isRequired.value = Boolean(Number(state.value.isRequired))
            isSaleAttribute.value = Boolean(Number(state.value.isSaleAttribute))
        }
    }
})

const disabledFieldProps = computed(() => {
    return {
        disabled: attributeDialogType.value === 'view',
        maxlength: 20,
    }
})

const columns: PlusColumn[] = [
    {
        fieldProps: disabledFieldProps,
        label: '属性名称',
        prop: 'attributeName',
    },
    {
        label: '属性设置',
        prop: 'attributeSet',
    },
    // {
    //     label: '属性值类型',
    //     options: [
    //         { label: '文本', value: 1 },
    //     ],
    //     prop: 'attributeType',
    //     valueType: 'select',

    // },
    {
        label: '属性值',
        prop: 'attributeValue',
    },
]

function validateAttributeName(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入属性名称'))
    }
    if (pattern.test(value))
        callback(new Error('属性名称不允许输入空格'))

    else
        callback()
}

const rules = {
    attributeName: [
        {
            required: true,
            trigger: ['blur', 'change'],
            validator: validateAttributeName,
        },
    ],
    // attributeType: [
    //     {
    //         message: '请选择属性值类型',
    //         required: true,
    //     },
    // ],
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            ...state.value,
            attributeValue: attributeValueList.value.filter(item => item.value),
            isCustom: isCustom.value ? 1 : 0,
            isRequired: isRequired.value ? 1 : 0,
            isSaleAttribute: isSaleAttribute.value ? 1 : 0,
        }
        delete params.attributeType
        console.log(params)

        const fn = attributeId.value ? editCategoryAttributeMutate : addCategoryAttributeMutate

        fn(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                emits('success')
                cancel()
            },
        })
    }
}

const isRepetition = ref(false)
function checkRepetition(obj) {
    console.log(obj)
    // const list = attributeValueList.value.filter(item => item.value).map(item => item.value).slice(0, attributeValueList.value.length - 1)
    // if (list.length > 0 && list.includes(obj.value)) {
    //     createMessage.warning('属性值不能重复')
    //     obj.value = ''
    //     isRepetition.value = true
    // }
    // else {
    //     isRepetition.value = false
    // }
}

function delAttributeValue(index: number) {
    if (attributeValueList.value.length === 1) {
        createMessage.warning('至少保留一个属性值')
        return
    }
    attributeValueList.value.splice(index, 1)
}

function addAttributeValue() {
    if (attributeValueList.value[attributeValueList.value.length - 1].value === '') {
        createMessage.warning('请先填写属性值')
        return false
    }
    else {
        if (!isRepetition.value) {
            attributeValueList.value.push({ value: '' })
        }
    }
}

function cancel() {
    attributeVisible.value = false
}

function reset() {
    formRef.value.formInstance.clearValidate('attributeName')
    attributeValueList.value = [{ value: '' }]
    attributeDialogType.value = ''
    attributeId.value = ''
    isRequired.value = false
    isSaleAttribute.value = false
    isCustom.value = false
    state.value.attributeName = ''
    // formRef.value.formInstance.resetFields()
}
</script>

<template>
    <PlusDialog v-model="attributeVisible"
                :title="title"
                width="600"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="attributeInfoLoading"
                    animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
        >
            <template #plus-field-attributeSet>
                <el-checkbox v-model="isRequired"
                             label="必填"
                             size="large"
                             :disabled="attributeDialogType === 'view' || attributeDialogType === 'edit'"
                />

                <el-checkbox v-model="isSaleAttribute"
                             label="销售属性"
                             size="large"
                             :disabled="attributeDialogType === 'view' || attributeDialogType === 'edit'"
                />

                <el-checkbox v-model="isCustom"
                             label="允许自定义"
                             size="large"
                             :disabled="attributeDialogType === 'view' || attributeDialogType === 'edit'"
                />
            </template>

            <template #plus-field-attributeValue>
                <div v-for="(item, index) in attributeValueList"
                     :key="index"
                     class="w-full"
                >
                    <div class="mb-10 flex">
                        <el-input v-model="item.value"
                                  :disabled="attributeDialogType === 'view'"
                                  @change="checkRepetition(item)"
                        />

                        <span v-if="attributeDialogType !== 'view'"
                              class="pl-20 text-blue-600 w-60 cursor-pointer"
                              @click="delAttributeValue(index)"
                        >删除</span>
                    </div>
                </div>

                <div class="mt-10 w-412">
                    <SubmitBtn v-if="attributeDialogType !== 'view'"
                               class="w-full cursor-pointer"
                               @click="addAttributeValue()"
                    >
                        新增属性值
                    </SubmitBtn>
                </div>
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    {{ attributeDialogType === 'view' ? '关闭' : '取消' }}
                </el-button>

                <SubmitBtn v-if="attributeDialogType !== 'view'"
                           type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
